package com.kude.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.util.PropertyFilter;

import com.kude.entity.Product;
import com.kude.entity.ProductCategory;
import com.kude.manager.OperException;
import com.kude.service.ProductCategoryService;
import com.kude.util.BeanFactory;

public class GetSubProductCategoryServlet extends HttpServlet {
	ProductCategoryService productCategoryService;

	/**
	 * Constructor of the object.
	 */
	public GetSubProductCategoryServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		productCategoryService = BeanFactory.getBean(ProductCategoryService.class.getName());
		String operation = request.getParameter("operation");
		if (operation.equals("add")) {
			try {
				this.add(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("update")) {
			try {
				this.update(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("delete")) {
			try {
				this.delete(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("getProductCategoryByPrefix")) {
			try {
				this.getProductCategoryByPrefix(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("getProductCategoryByParentId")) {
			try {
				this.getProductCategoryByParentId(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
/**
 * 根据ParentId获取类别，parentId为0为第二层类别
 * @param request
 * @param response
 * @throws Exception
 */
	private void getProductCategoryByParentId(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int id = Integer.parseInt(request.getParameter("parentId"));
		
		JsonConfig config = new JsonConfig();
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        config.setJsonPropertyFilter(new PropertyFilter() {
            public boolean apply(Object source, String name, Object value) {
                if (name.equals("productCategory")||name.equals("products")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
		
		JSONArray productCategoryList = JSONArray
				.fromObject(productCategoryService
						.getProductCategoryListByParentId(id),config);
		response.getWriter().write(productCategoryList.toString());
		response.getWriter().flush();
	}
	

	private void getProductCategoryByPrefix(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String prefix = request.getParameter("prefix");
		JsonConfig config = new JsonConfig();
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        config.setJsonPropertyFilter(new PropertyFilter() {
            public boolean apply(Object source, String name, Object value) {
                if (name.equals("productCategory")||name.equals("products")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
		JSONArray productCategoryList = JSONArray
				.fromObject(productCategoryService
						.getProductCategoryListByPrefix(prefix),config);
		response.getWriter().write(productCategoryList.toString());
		response.getWriter().flush();
	}
    
	private void delete(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		int id = Integer.parseInt(request
				.getParameter("productCategoryPrefixId"));
		try {
			productCategoryService.deleteProductCategory(id);
			response.getWriter().write("1");
			response.getWriter().flush();
		} catch (OperException e) {
			response.getWriter().write("0");
			response.getWriter().flush();
		}

	}

	private void update(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			ProductCategory productCategory = new ProductCategory();
			// TODO 把需要更新的字段更新
			productCategoryService.updateProductCategory(productCategory);
			response.getWriter().write("1");
			response.getWriter().flush();
		} catch (OperException e) {
			response.getWriter().write("0");
			response.getWriter().flush();
		}

	}

	private void add(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			ProductCategory productCategory = new ProductCategory();
			// TODO 把字段更新
			productCategoryService.addProductCategory(productCategory);
			response.getWriter().write("1");
			response.getWriter().flush();
		} catch (OperException e) {
			response.getWriter().write("0");
			response.getWriter().flush();
		}

	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
